package com.rutas.java;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class CapaMyPos extends ItemizedOverlay<OverlayItem> {
	private Context contexto;
	public OverlayItem puntoGPS;
	private Handler handlerGeocoder = new Handler(){
		@Override
		public void handleMessage(Message msg){
			Address direc = (Address) msg.obj;
			int ind = direc.getMaxAddressLineIndex();
			String texto = "";
			for (int i = 0; i < ind; i++){
				texto += direc.getAddressLine(i)+ ", ";
			}
			if (!texto.contentEquals("")){
				texto = texto.substring(0, texto.length() - 2);
				Toast myToast = Toast.makeText(contexto, texto, Toast.LENGTH_LONG);
				//Toast.makeText(contexto, direc.getLocality() +"\n"+ direc.getSubAdminArea(), Toast.LENGTH_SHORT).show();
				View v = myToast.getView();
				v.setBackgroundResource(R.layout.border);
				myToast.setView(v);
				myToast.show();
			}
		}
	};
	
	public CapaMyPos(Drawable defaultMarker, Context c, OverlayItem miItem){
		super(boundCenter(defaultMarker));
		contexto = c;
		puntoGPS = miItem;
		populate();
	}

	@Override 
	protected OverlayItem createItem(int i) {
		return puntoGPS;
	}

	@Override
	public int size() {
		return 1;
	}
	@Override 
	public void draw(Canvas c, MapView m, boolean shadow) { 
		if (!shadow) 
			super.draw(c, m, shadow); 
		}
	
	@Override
	protected boolean onTap(int index){	
		//lanza thread con consulta de posicion
		new Thread (new Runnable(){
			public void run(){
				Geocoder geocoder = new Geocoder(contexto, Locale.getDefault());
				try {
					List<Address> direcciones = geocoder.getFromLocation
								(puntoGPS.getPoint().getLatitudeE6() / 1E6, puntoGPS.getPoint().getLongitudeE6() / 1E6, 1);
					if (!direcciones.isEmpty()){
						Address direccion = direcciones.get(0);
						Message mensaje = new Message();
						mensaje.obj = direccion;
						handlerGeocoder.sendMessage(mensaje);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}		
			}
		}).start();
		return true;
	}
}
